/**
 * Created by root on 2015/1/13.
 */
var doPage = function(page, limit){
    $.post('/admin/question', {
        store: $('#js-store').val(),
        page: page,
        limit: limit
    }, function(res){
        var result = res.result;
        var count = res.count;
        var pageCount = res.pageCount;
        var currentPage = res.currentPage;
        var limit = res.limit;

        var oPageUl = $('#js-page');
        var oStart = $('#js-start')
        var oEnd = $('#js-end');
        var oTotal = $('#js-total');
        var oUserBody = $('#js-user-body');

        oStart.text((currentPage - 1) * limit + 1);
        oEnd.text((currentPage * limit) > count ? count : (currentPage * limit));
        oTotal.text(count);

        var html = '';
        for(var i= 0,len=result.length; i < len;i++){
            var data = result[i];
            var os = [];
            var opts = data['opts']
            for (var j = 0; j < opts.length; j++) {
                var obj = opts[j];
                os.push(obj['idx'] + '、' + obj['text']);
            }

            html += '<tr>';
            html += '<td><p class="text-left tb-text"><textarea style="width:100%;resize:none;" rows="5" data-qid="' + data._id + '" data-origin="' + data.text + '"  name="text">' + (data.text || '') + '</textarea></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + (data.profession || '')  + '</p></td>';

            //html += '<td><p class="text-left tb-text"><input type="text" data-qid="' + data._id + '" data-origin="' + data.opts + '"  name="opts" value="' + (data.opts || '') + '"/></p></td>';
            html +=	'<td><p class="text-left tb-text">' + os.join('<br/>') + '</p></td>';

            html += '<td><p class="text-left tb-text"><input type="text" data-qid="' + data._id + '" data-origin="' + data.answer + '"  name="answer" value="' + (data.answer || '') + '"/></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + data.score + '</p></td>';

            html += '<td><p class="text-left tb-text"><input type="text" class="" data-qid="' + data._id + '" data-origin="' + data.score + '"  name="score" value="' + (data.score || 0) + '"/></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + data.duration + '</p></td>';

            //html += '<td><p class="text-center tb-text"><a class="btn mini black"><i class="icon-trash"></i> 删除</a></p></td>';
            html += '</tr>';
        }
        oUserBody.html(html);

        var page = '';
        if(currentPage > 1){
            page += '<li class="prev"><a data-page="' + (currentPage - 1) + '">← 上一页</a></li>';
            if(currentPage > 4){
                page += '<li><a data-page="1">' + 1 + '</a></li>';
            }
            if(currentPage > 5){
                page += '<li class="disabled"><a> ... </a></li>';
            }
        }

        for(var i=3; i > 0; i--){
            if((currentPage - i) > 0){
                page += '<li class=""><a data-page="' + (currentPage - i) + '">' + (currentPage - i) + '</a></li>';
            }
        }

        for(var i=currentPage;i<=pageCount;i++){
            if(i == (currentPage + 4)){
                break;
            }
            if(i == currentPage){
                page += '<li class="active"><a>' + i + '</a></li>';
            } else {
                page += '<li class=""><a  data-page="' + i + '">' + i + '</a></li>';
            }
        }

        if(pageCount != currentPage){

            if(currentPage < (pageCount - 4)){
                page += '<li class="disabled"><a> ... </a></li>';
            }

            if(currentPage < (pageCount - 3)){
                page += '<li><a data-page="' + pageCount + '">' + pageCount + '</a></li>';
            }
            page += '<li class="next"><a  data-page="' + (currentPage + 1) + '">下一页 → </a></li>';
        }
        oPageUl.html(page);

        oPageUl.delegate('li', 'click', function () {
            if($(this).hasClass('disabled') || $(this).hasClass('active')){
                return;
            }
            var page = $(this).find('a').data('page');
            doPage(page, 10);
        });
    }, 'json');
}

$(function(){
    doPage(1, 10);
});

/**
 * var oUserBody = $('#js-user-body');
 */

var oUserBody = $('#js-user-body');


oUserBody.delegate('input,textarea', 'blur', function () {
    var oTr = $(this).closest('tr');
    oTextInput = oTr.find('textarea[name="text"]');
    oAnswerInput = oTr.find('input[name="answer"]');
    oScoreInput = oTr.find('input[name="score"]');

    var value = $(this).val();
    var origin = $(this).data('origin');
    var answers = [];
    if(value != origin){

        var answer = oAnswerInput.val();
        if(!answer){
            var d = dialog({
                content: '必须填写至少一个正确答案'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 1000);
            return;
        } else {
            if(answer.substr(-1,1) === ','){
                answer = answer.substring(0, answer.length - 1);
            }
            answer = answer.replace(/，/g, ',').replace(/ /g, ''); //讲中文，转为因为, 将空格去掉
            answers = answer.split(',');
            for(var i=0;i<answers.length;i++){
                var ans = answers[i].toUpperCase();
                if(ans.length > 1){
                    var d = dialog({
                        content: '答案好像不符合格式,请检查!'
                    });
                    d.showModal();
                    setTimeout(function () {
                        d.close().remove();
                    }, 1000);
                    return;
                } else {
                    answers[i] = ans;
                }
            }
        }

        $.post('/admin/updateQuestion', {
            text: oTextInput.val(),
            answer: answers,
            score: oScoreInput.val(),
            qid: $(this).data('qid')
        }, function(res){
            var d = dialog({
                content: '修改成功'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 1000);
        });
    }
})
